<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      .big {
        width: 600px;
        height: 600px;
        border: 5px solid palegreen;
        position: relative;
      }
      .big div {
        width: 30%;
        height: 30%;
        background: lawngreen;
        position: absolute;
        font-size: 50px;
        color: white;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 5px;
      }
    </style>
  </head>
  <body>
    <div class="big">
      <div style="left: 2%; top: 2%">1</div>
      <div style="left: 35%; top: 2%">2</div>
      <div style="left: 68%; top: 2%">3</div>
      <div style="left: 2%; top: 35%">4</div>
      <div style="left: 35%; top: 35%">5</div>
      <div style="left: 68%; top: 35%">6</div>
      <div style="left: 2%; top: 68%">7</div>
      <div style="left: 35%; top: 68%">8</div>
      <div style="left: 68%; top: 68%">9</div>
    </div>
    <script>
      var divEle = document.querySelectorAll(".big div");
      var arr = [
        "lawngreen",
        "teal",
        "yellow",
        "orange",
        "slateblue",
        "pink",
        "palegreen",
        "purple",
        "green",
      ];
      Array.from(divEle).forEach(function (item, i) {
        item.style.backgroundColor = arr[i];
      });

      Array.from(divEle).forEach(function (item) {
        item.onmousedown = function (e) {
          item.style.zIndex = 10;
          //获取光标在盒子中的相对位置~
          var e = e || window.e;
          var x = e.clientX - item.offsetLeft;
          var y = e.clientY - item.offsetTop;

          item.onmousemove = function (event) {
            //盒子的光标跟随
            var event = event || window.event;
            var xx = event.clientX - x;
            var yy = event.clientY - y; //计算移动之后盒子偏移量
            item.style.left = `${xx}px`;
            item.style.top = `${yy}px`;
          };
          document.onmouseup = function () {
            item.onmousemove = "";
            item.style.zIndex = 0;
          };
        };
      });
    </script>
  </body>
</html>
